/**
 * 用户级Token
 */

const Qs = require('querystring')
const Request = require('../request')
const { tokenLogger } = require('./util')
const { CacheUtil } = require('./cache')
const { T_USER } = require('./dbHelper')

// 简易缓存过期时间
const lastTime = {
}
const interval = 30 * 1000

const REQ_URL = {
  'mirror': 'https://logintestlf.hwcloudtest.cn/oauth2/v2/token',
  'prod': 'https://login.cloud.huawei.com/oauth2/v2/token'
}

/**
 * 使用 rt 刷 at
 * @param rt
 * @returns {Q.Promise<unknown>}
 */
async function genUserToken({ id, env }) {
  env = env.toUpperCase()
  const CACHE_KEY = `${env}_USER_${id}`
  if (!isExpired(CACHE_KEY, interval)) {
    return Promise.resolve(CacheUtil.get(CACHE_KEY))
  }
  const rets = await T_USER.query(`id = ${id}`)
  if (rets.length <= 0) {
    throw new Error('传入的id未查到数据')
  }
  const { refreshtoken, appid, appsecret } = rets[0]
  const RT_KEY = 'refresh_token'
  return Request.post(REQ_URL[`${env}`.toLowerCase()], Qs.stringify({
    grant_type: RT_KEY,
    refresh_token: refreshtoken,
    client_id: appid,
    client_secret: appsecret
  }), {
    'Content-Type': 'application/x-www-form-urlencoded'
  }).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    lastTime[CACHE_KEY] = Date.now()
    CacheUtil.put(CACHE_KEY, data)

    if (data[RT_KEY]) {
      // 更新数据库中的RT为最新的RT
      updateRefreshToken(id, data[RT_KEY])
    }
    return data
  }).catch(err => {
    // handle err
    throw new Error(`获取用户级token失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

/**
 * 查找 user list
 */
async function getUserList(env) {
  tokenLogger('info', 'query', `begin query table ${T_USER.tableName} with env is ${env}`)
  const envMapper = {
    'mirror': 0,
    'prod': 1
  }
  if (env !== undefined) {
    const tmpEnv = envMapper[`${env}`.toLowerCase()]
    if (tmpEnv !== undefined) {
      return await T_USER.query(`env = ${tmpEnv}`)
    }
  }
  return await T_USER.query()
}

/**
 * 检查缓存是否过期
 * 1. lastTime 为空
 * 2. nowTime - lastTime < 30s
 */
function isExpired(env, interval = 30 * 1000) {
  return lastTime[env] === undefined || Date.now() - lastTime[env] > interval
}

/**
 * 更新数据库中的RT
 */
async function updateRefreshToken(id, refreshtoken) {
  return await T_USER.updateRTById(id, refreshtoken)
}

module.exports = { genUserToken, getUserList }
